<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\DB;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            $type = $request->input('momeType') ? $request->input('momeType') : 2;
            $time = time();
            if ($type == 1) {
                //ipad
                $token = $request->input('authtoken');
                if (!empty($token)) {
                    $res = DB::table('multiDeviceLogin')->where('token', $token)->where('validity', '>', $time)->first();
                    if(!empty($res)){
                        return User::find($res->uid);
                    }
                }
            } else if ($type == 2) {
                //web
                $token = $request->header('authtoken');
                if (!empty($token)) {
                   return User::where('apiToken', $token)->where('validity', '>', $time)->first();
                }
            }
        });
    }
}
